import { createConsumer } from './question-hub'

const PRESENCE_INTERVAL = 1000 * 60 * 1

class BaseActionCableConnector {
  constructor (app, accountId, userId, token) {
    this.consumer = createConsumer(this.onConnected, this.onReceived, accountId, userId, token)
    this.app = app
    this.events = {}
    this._connectionId = ''
    this.isAValidEvent = () => true

    setInterval(() => {
      this.consumer.invoke('updatePresenceAsync', {
        channel: 'RoomChannel',
        accountId: accountId,
        userId: userId,
        type: 'User'
      })
    }, PRESENCE_INTERVAL)
  }

  disconnect () {
    this.consumer.stop()
  }

  get connectionId () {
    return this._connectionId
  }

  onConnected = (connectionId) => {
    console.log(connectionId)
    this._connectionId = connectionId
  }

  onReceived = ({ event, data } = {}) => {
    if (this.isAValidEvent(data)) {
      if (this.events[event] && typeof this.events[event] === 'function') {
        this.events[event](data)
      }
    }
  }
}

export default BaseActionCableConnector
